// 请用shadcn/ui写一个antd中upload功能一样的组件
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { useRef, useState, useEffect } from "react";

interface CustomUploaderProps {
  data: File[];
  onChange: (files: File[]) => void;
  accept?: string;
}

function CustomUploader({
  data,
  onChange,
  accept = "image/*",
}: CustomUploaderProps) {
  const [fileList, setFileList] = useState<File[]>([]);
  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    // console.log("handleFileChange");
    // console.log(event.target.files);
    if (event.target.files) {
      onChange(Array.from(event.target.files));
      setFileList(Array.from(event.target.files));
    }
  };

  // 点击拖拽上传框时，触发文件选择框
  const handleUploadClick = () => {
    fileInputRef.current?.click();
  };

  const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    if (event.dataTransfer.files) {
      onChange(Array.from(event.dataTransfer.files));
      setFileList(Array.from(event.dataTransfer.files));
    }
  };

  const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
    event.preventDefault();
  };

  const handleDelete = (index: number) => {
    setFileList((prevList) => prevList.filter((_, i) => i !== index));
    onChange(fileList.filter((_, i) => i !== index));
  };

  useEffect(() => {
    if (data && data.length > 0) {
      setFileList(data);
    }
  }, [data]);

  return (
    <div>
      <div
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onClick={handleUploadClick}
        style={{
          border: "2px dashed #ccc",
          padding: "20px",
          textAlign: "center",
        }}
      >
        拖拽文件到此处或点击上传
        <Input
          type="file"
          ref={fileInputRef}
          accept={accept}
          onChange={handleFileChange}
          style={{ display: "none" }}
          multiple
        />
      </div>
      {/* 展示已选择的文件 */}
      <ul>
        {fileList.map((file: File, index) => (
          <li
            key={index}
            style={{ display: "flex", justifyContent: "space-between" }}
          >
            <span>{file.name || "文件"}</span>
            <button onClick={() => handleDelete(index)}>删除</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default CustomUploader;
